package gf

import (
	"fmt"
	"time"

	"test/lib/goframe/in"
	"test/lib/goframe/middle"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtimer"
)

type Server struct {
	Port int //端口
	*ghttp.Server
}

/*

//cpu检测
go tool pprof http://localhost:6060/pprof/profile?seconds=20

//内存检测
go tool pprof http://localhost:6060/pprof/heap

*/
//快速开始默认配置
//@port,端口
func New(port int) *Server {
	s := g.Server()
	s.SetPort(port)
	s.Plugin(&Swagger{})
	s.EnablePProf("/pprof")      //性能调试
	s.SetAccessLogEnabled(false) //请求日志
	s.SetErrorLogEnabled(false)  //错误日志
	s.BindStatusHandler(404, func(r *ghttp.Request) {
		r.Response.ClearBuffer()
		in.Return(r, 404, in.PageNotFind_robot)
	})
	middle.UseCors()
	gtimer.AddOnce(time.Second, func() {
		fmt.Printf("打开接口文档: 点击 http://127.0.0.1:%d/swagger 	\n", port)
		fmt.Printf("打开性能剖析: 点击 http://127.0.0.1:%d/pprof 	\n", port)
	})
	return &Server{port, s}
}

func (this *Server) All(s string, fn func(r *ghttp.Request)) *Server {
	if fn != nil {
		g.Server().Group("", func(g *ghttp.RouterGroup) {
			g.ALL(s, fn)
		})
	}
	return this
}

func (this *Server) Get(s string, fn func(r *ghttp.Request)) *Server {
	if fn != nil {
		g.Server().Group("", func(g *ghttp.RouterGroup) {
			g.GET(s, fn)
		})
	}
	return this
}

func (this *Server) Post(s string, fn func(r *ghttp.Request)) *Server {
	if fn != nil {
		g.Server().Group("", func(g *ghttp.RouterGroup) {
			g.POST(s, fn)
		})
	}
	return this
}

func (this *Server) Put(s string, fn func(r *ghttp.Request)) *Server {
	if fn != nil {
		g.Server().Group("", func(g *ghttp.RouterGroup) {
			g.PUT(s, fn)
		})
	}
	return this
}

func (this *Server) Delete(s string, fn func(r *ghttp.Request)) *Server {
	if fn != nil {
		g.Server().Group("", func(g *ghttp.RouterGroup) {
			g.DELETE(s, fn)
		})
	}
	return this
}

func (this *Server) Run() {
	g.Server().Run()
}
